package jhunter.rt.conf.ext;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import jhunter.conf.entities.vo.Entities;
import jhunter.conf.entities.vo.Entity;
import jhunter.rt.conf.Node;
import jhunter.rt.conf.Reloadable;

public class EntitiesExt implements Reloadable {

	private static Log log = LogFactory.getLog(EntitiesExt.class);

	private Entities entities;

	private Node node;

	public EntitiesExt(Entities entities, Node node) {
		super();
		this.entities = entities;
		this.node = node;
	}

	public Entities getEntities() {
		return entities;
	}

	public void setEntities(Entities entities) {
		this.entities = entities;
	}

	public Node getNode() {
		return node;
	}

	public void setNode(Node node) {
		this.node = node;
	}

	public List<String> getEntityids() {
		List<String> list = new ArrayList<String>();
		for (Entity e : this.entities.getEntity()) {
			list.add(e.getId());
		}
		return list;
	}

	@Override
	public void unload() {
		AppExt ae = getAppExt();
		for (String id : getEntityids()) {
			ae.removeEntity(id);
			log.debug(" remove entity :" + id);
		}
	}

	protected AppExt getAppExt() {
		AppExt ae = (AppExt) this.node.getParent().getParent().getObject();
		return ae;
	}

	@Override
	public void afterLoad() {
		AppExt ae = getAppExt();
		for (Entity e : this.entities.getEntity()) {
			ae.registEntity(e);
			log.debug("regist enttiy :" + e.getId());
		}
		
		ae.mergeTable(this.getEntityids());
	}

	@Override
	public void init() {
		AppExt ae = getAppExt();
		for (Entity e : this.entities.getEntity()) {
			ae.registEntity(e);
			log.debug("init enttiy :" + e.getId());
		}
	}

}
